package com.beiding.jsonanalyzer.flow;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.beiding.jsonanalyzer.Analyzer;
import com.beiding.jsonanalyzer.analyze.KeyMode;
import com.beiding.jsonanalyzer.analyze.KeyUtils;
import com.beiding.jsonanalyzer.analyze.ValueUtils;

/**
 * 值节点
 * 类比单行数据
 *
 * @author 丁常磊
 * @date 2022/4/21 10:05
 */

public class ValueNode {

    /**
     * 当前节点的值
     */
    private Object value;


    public ValueNode() {
    }

    public Object get() {
        return value;
    }


    public void set(Object value) {
        this.value = value;
    }

    public Object get(Object key) {
        Object handleKey = KeyUtils.handleKey(key, KeyMode.TEXT_TO_KEY);
        return ValueUtils.execExpression(value, handleKey, Object.class);
    }

    public <T> T get(Object key, Class<T> type) {
        Object handleKey = KeyUtils.handleKey(key, KeyMode.TEXT_TO_KEY);
        Object t = ValueUtils.execExpression(value, handleKey, type);
        if (type.isInstance(t)) {
            return (T) t;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("o", t);

        return jsonObject.getObject("o", type);
    }


    public String getString(Object key) {
        return get(key, String.class);
    }

    public Integer getInt(Object key) {
        return get(key, Integer.class);
    }

    public Long getLong(Object key) {
        return get(key, Long.class);
    }

    public Short getShort(Object key) {
        return get(key, Short.class);
    }

    public Boolean getBoolean(Object key) {
        return get(key, Boolean.class);
    }

    public Byte getByte(Object key) {
        return get(key, Byte.class);
    }

    public Double getDouble(Object key) {
        return get(key, Double.class);
    }

    public Float getFloat(Object key) {
        return get(key, Float.class);
    }

    public Character getChar(Object key) {
        return get(key, Character.class);
    }

    public JSONObject getJsonObject(Object key) {
        return get(key, JSONObject.class);
    }

    public JSONArray getJsonArray(Object key) {
        return get(key, JSONArray.class);
    }

    public String format() {
        return Analyzer.format(this.value);
    }

    public String format(String tab) {
        return Analyzer.format(this.value, tab);
    }

}
